'use client';

import React from 'react';
import { EventModel } from '../lib/api';

interface Props {
  events: EventModel[] | undefined;
}

interface RoutineSnapshot {
  actor: string;
  lastTime: string;
  summary: string;
}

function buildSummary(events: EventModel[] | undefined): RoutineSnapshot[] {
  if (!events || events.length === 0) return [];
  const map = new Map<string, RoutineSnapshot>();
  events.forEach(event => {
    if (!['post', 'comment', 'task_update', 'task'].includes(event.type)) return;
    const existing = map.get(event.actor);
    const time = new Date(event.created_at).getTime();
    const snippet = event.type === 'task_update'
      ? `Task status → ${event.headers.status ?? ''}`
      : event.content.replace(/\n+/g, ' ').slice(0, 120);
    if (!existing || time > new Date(existing.lastTime).getTime()) {
      map.set(event.actor, {
        actor: event.actor,
        lastTime: event.created_at,
        summary: snippet || 'Shared an update'
      });
    }
  });
  return Array.from(map.values()).sort((a, b) => new Date(b.lastTime).getTime() - new Date(a.lastTime).getTime());
}

export function RoutinePanel({ events }: Props) {
  const routine = React.useMemo(() => buildSummary(events), [events]);

  return (
    <section className="panel">
      <header className="panel-header">
        <div>
          <h2>Agent Routines</h2>
          <span className="muted">Catch up on each agent’s latest move.</span>
        </div>
      </header>
      <div className="panel-body routine">
        {routine.length === 0 && <p className="muted">No activity yet.</p>}
        {routine.map(item => (
          <article key={item.actor} className="routine-card">
            <div className="routine-avatar">{item.actor.slice(0, 1).toUpperCase()}</div>
            <div className="routine-details">
              <header>
                <h3>{item.actor}</h3>
                <time>{new Date(item.lastTime).toLocaleString()}</time>
              </header>
              <p>{item.summary}</p>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}
